/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.Consequent;
import it.polimi.games.epkb.entityClasses.ConsequentPK;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.GpiKpi;
import it.polimi.games.epkb.entityClasses.AssociationRule;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class ConsequentJpaController implements Serializable {

    public ConsequentJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public ConsequentJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Consequent consequent) throws PreexistingEntityException, Exception {
        if (consequent.getConsequentPK() == null) {
            consequent.setConsequentPK(new ConsequentPK());
        }
        consequent.getConsequentPK().setIdGPIKPI(consequent.getGpiKpi().getId());
        consequent.getConsequentPK().setIdRule(consequent.getAssociationRule().getId());
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            GpiKpi gpiKpi = consequent.getGpiKpi();
            if (gpiKpi != null) {
                gpiKpi = em.getReference(gpiKpi.getClass(), gpiKpi.getId());
                consequent.setGpiKpi(gpiKpi);
            }
            AssociationRule associationRule = consequent.getAssociationRule();
            if (associationRule != null) {
                associationRule = em.getReference(associationRule.getClass(), associationRule.getId());
                consequent.setAssociationRule(associationRule);
            }
            em.persist(consequent);
            if (gpiKpi != null) {
                gpiKpi.getConsequentCollection().add(consequent);
                gpiKpi = em.merge(gpiKpi);
            }
            if (associationRule != null) {
                associationRule.getConsequentCollection().add(consequent);
                associationRule = em.merge(associationRule);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findConsequent(consequent.getConsequentPK()) != null) {
                throw new PreexistingEntityException("Consequent " + consequent + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Consequent consequent) throws NonexistentEntityException, Exception {
        consequent.getConsequentPK().setIdGPIKPI(consequent.getGpiKpi().getId());
        consequent.getConsequentPK().setIdRule(consequent.getAssociationRule().getId());
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Consequent persistentConsequent = em.find(Consequent.class, consequent.getConsequentPK());
            GpiKpi gpiKpiOld = persistentConsequent.getGpiKpi();
            GpiKpi gpiKpiNew = consequent.getGpiKpi();
            AssociationRule associationRuleOld = persistentConsequent.getAssociationRule();
            AssociationRule associationRuleNew = consequent.getAssociationRule();
            if (gpiKpiNew != null) {
                gpiKpiNew = em.getReference(gpiKpiNew.getClass(), gpiKpiNew.getId());
                consequent.setGpiKpi(gpiKpiNew);
            }
            if (associationRuleNew != null) {
                associationRuleNew = em.getReference(associationRuleNew.getClass(), associationRuleNew.getId());
                consequent.setAssociationRule(associationRuleNew);
            }
            consequent = em.merge(consequent);
            if (gpiKpiOld != null && !gpiKpiOld.equals(gpiKpiNew)) {
                gpiKpiOld.getConsequentCollection().remove(consequent);
                gpiKpiOld = em.merge(gpiKpiOld);
            }
            if (gpiKpiNew != null && !gpiKpiNew.equals(gpiKpiOld)) {
                gpiKpiNew.getConsequentCollection().add(consequent);
                gpiKpiNew = em.merge(gpiKpiNew);
            }
            if (associationRuleOld != null && !associationRuleOld.equals(associationRuleNew)) {
                associationRuleOld.getConsequentCollection().remove(consequent);
                associationRuleOld = em.merge(associationRuleOld);
            }
            if (associationRuleNew != null && !associationRuleNew.equals(associationRuleOld)) {
                associationRuleNew.getConsequentCollection().add(consequent);
                associationRuleNew = em.merge(associationRuleNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                ConsequentPK id = consequent.getConsequentPK();
                if (findConsequent(id) == null) {
                    throw new NonexistentEntityException("The consequent with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(ConsequentPK id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Consequent consequent;
            try {
                consequent = em.getReference(Consequent.class, id);
                consequent.getConsequentPK();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The consequent with id " + id + " no longer exists.", enfe);
            }
            GpiKpi gpiKpi = consequent.getGpiKpi();
            if (gpiKpi != null) {
                gpiKpi.getConsequentCollection().remove(consequent);
                gpiKpi = em.merge(gpiKpi);
            }
            AssociationRule associationRule = consequent.getAssociationRule();
            if (associationRule != null) {
                associationRule.getConsequentCollection().remove(consequent);
                associationRule = em.merge(associationRule);
            }
            em.remove(consequent);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Consequent> findConsequentEntities() {
        return findConsequentEntities(true, -1, -1);
    }

    public List<Consequent> findConsequentEntities(int maxResults, int firstResult) {
        return findConsequentEntities(false, maxResults, firstResult);
    }

    private List<Consequent> findConsequentEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Consequent.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Consequent findConsequent(ConsequentPK id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Consequent.class, id);
        } finally {
            em.close();
        }
    }

    public int getConsequentCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Consequent> rt = cq.from(Consequent.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
